import { faker } from '@faker-js/faker';
import { delay, http, HttpResponse } from 'msw';
import { formateSuccessResp } from '../utils';

import { UserApi } from '@/api/services/userService';

import { USER_LIST } from '../assets';

const signIn = http.post(`/api${UserApi.SignIn}`, async ({ request }) => {
  const { account, password } = (await request.json()) as any;
  await delay(2000);
  const user = USER_LIST.find((item) => item.account === account);

  if (!user || user.password !== password) {
    return HttpResponse.json({
      code: 10001,
      message: 'Incorrect account or password.',
    });
  }

  return formateSuccessResp({ token: faker.string.uuid() });
});

const userInfo = http.get(`/api${UserApi.UserInfo}`, async () => {
  await delay(1000);
  return HttpResponse.json({
    code: 200,
    message: '',
    data: USER_LIST[0],
  });
}
)

const userList = http.get('/api/user', async () => {
  await delay(1000);
  return HttpResponse.json(
    Array.from({ length: 10 }).map(() => ({
      fullname: faker.person.fullName(),
      email: faker.internet.email(),
      avatar: faker.image.avatar(),
      address: faker.location.streetAddress(),
    })),
    {
      status: 200,
    },
  );
});

const deleteUser = http.delete(`/api${UserApi.Delete}/:id`, async ({ params }) => {
  await delay(1000);
  const { id } = params;
  // 从 USER_LIST 找到 id 对应的用户并删除
  const index = USER_LIST.findIndex((item) => item.id === id);
  USER_LIST.splice(index, 1);
  return HttpResponse.json({
    status: 0,
    message: '删除成功',
    data: params.id,
  });
});

const getUserList = http.get(`/api${UserApi.List}`, async () => {
  await delay(1000);
  return formateSuccessResp(USER_LIST);
});

export default [signIn, userInfo, userList, deleteUser, getUserList];
